import os,shutil,subprocess,config,sys
from PyQt5.QtCore import QThread,pyqtSignal

class ExtractFSB(QThread):
  workerFinished = pyqtSignal(object)
  oneFileFinished = pyqtSignal()
  workerError = pyqtSignal(object)
  def __init__(self,startIndex,endIndex,filePaths):
    super(ExtractFSB,self).__init__()
    self.startIndex = startIndex
    self.endIndex = endIndex
    self.filePaths = filePaths

  def run(self):
    for i in range(self.startIndex,self.endIndex):
      path = self.filePaths[i]
      extractDirName = os.path.splitext(os.path.basename(path))[0].replace("_crypt","")
      extractDirPath = os.path.join(config.extractDir,extractDirName)

      # 清上次结果
      if os.path.exists(extractDirPath):
          shutil.rmtree(extractDirPath)
      os.makedirs(extractDirPath)
      
      # 找缓存
      cachePath = os.path.join(config.cacheExtractDir,extractDirName)
      if os.path.exists(cachePath):
        shutil.copytree(cachePath,extractDirPath,dirs_exist_ok=True)
      else:
        print(path)
        result = subprocess.run([config.fmodextr,path],cwd=extractDirPath) #cwd 报错找不到输入文件 程序bug
        if result.returncode!=0:
          self.workerError.emit(self)
          return
        
        # cwd报错，移动根目录下的fsb到目标目录
        # 打包后wav生成到exe目录下去了！但是baseDir在internal同级目录
        # generatecDir = config.baseDir
        # if getattr(sys, 'frozen', False):
        #   generatecDir =  os.path.dirname(config.baseDir)

        # for filename in os.listdir(generatecDir):
        #   if filename.endswith(".wav"):
        #     filepath = os.path.join(config.baseDir,filename)
        #     os.rename(filepath,os.path.join(extractDirPath,filename))

        # 存缓存
        shutil.copytree(extractDirPath,cachePath)
      self.oneFileFinished.emit()

    self.workerFinished.emit(self)